# -*- coding: utf-8 -*-
"""
Qt6 输入对话框 - 用于替代 VBScript 的 multi_input_box
"""
from PyQt6.QtWidgets import (
    QApplication, QDialog, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QPushButton,QComboBox, QMessageBox
)
from PyQt6.QtCore import Qt
from multiprocessing import Process, Queue

from utils.logger import log

# 窗口管理器 - 防止多个输入窗口同时打开
_current_active_dialog = None

import json
from pathlib import Path

class InputHistoryManager:
    def __init__(self, data_dir: str):
        """初始化历史记录管理器"""
        self._data_dir = Path(data_dir)
        self._history_file = self._data_dir / "input_history.json"
        self._history_data = self._load_history()
    
    def _load_history(self):
        """加载历史记录文件"""
        if self._history_file.exists():
            try:
                with open(self._history_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    print(f"[HISTORY] 加载历史记录: {data}")
                    return data
            except Exception as e:
                print(f'[HISTORY] 加载历史记录失败: {e}')
        # 如果文件不存在或加载失败，返回空数据
        return {
            "project_name": [],
            "task_id": [], 
            "work_type": [],
            "workload1": [],
            "remark": []
        }
    
    def _save_history(self):
        """保存历史记录到文件"""
        try:
            with open(self._history_file, 'w', encoding='utf-8') as f:
                json.dump(self._history_data, f, ensure_ascii=False, indent=2)
            print(f"[HISTORY] 保存历史记录成功")
        except Exception as e:
            print(f'[HISTORY] 保存历史记录失败: {e}')
    
    def get_history(self, field_name, limit=10):
        """获取指定字段的历史记录"""
        history_list = self._history_data.get(field_name, [])
        # 返回指定数量的记录，最新的在前面
        return history_list[:limit]
    
    def add_history(self, field_name, value):
        """添加一条历史记录"""
        if not value or not value.strip():
            return
        
        # 确保该字段有历史记录列表
        if field_name not in self._history_data:
            self._history_data[field_name] = []
        
        history_list = self._history_data[field_name]
        
        # 移除重复的值（如果已存在）
        if value in history_list:
            history_list.remove(value)
        
        # 添加到列表开头（最新的在最前面）
        history_list.insert(0, value)
        
        # 限制历史记录数量（最多保存20条）
        if len(history_list) > 20:
            history_list = history_list[:20]
            self._history_data[field_name] = history_list
        
        # 保存到文件
        self._save_history()
        print(f"[HISTORY] 添加记录: {field_name} = {value}")

# 全局历史管理器实例
_history_manager = None

def init_history_manager(data_dir: str):
    """初始化历史管理器（在程序启动时调用）"""
    global _history_manager
    _history_manager = InputHistoryManager(data_dir)
    print(f"[HISTORY] 历史记录管理器初始化完成，数据目录: {data_dir}")

def get_history_manager():
    """获取历史管理器实例"""
    return _history_manager

def close_active_dialog():
    """关闭当前活跃的对话框"""
    global _current_active_dialog
    if _current_active_dialog is not None:
        try:
            # 尝试关闭对话框
            _current_active_dialog.reject()
            _current_active_dialog = None
            print("[窗口管理] 已关闭前一个对话框")
        except Exception as e:
            print(f"[窗口管理] 关闭对话框时出错: {e}")
            _current_active_dialog = None

def set_active_dialog(dialog):
    """设置当前活跃的对话框"""
    global _current_active_dialog
    # 先关闭之前可能存在的对话框
    close_active_dialog()
    # 设置新的对话框
    _current_active_dialog = dialog
    print("[窗口管理] 设置新的活跃对话框")

def clear_active_dialog():
    """清除当前对话框引用"""
    global _current_active_dialog
    _current_active_dialog = None
    print("[窗口管理] 清除对话框引用")

# 修改 qt6_input_dialog.py 中的函数签名

def qt_multi_input_box(title="录入", prompts=None, default_values=None, combo_items=None, 
                      header_text="", parent=None): 
    print("[QT6] qt_multi_input_box 被调用（主进程）")
    
    # ★★★ 先关闭可能存在的旧窗口 ★★★
    close_active_dialog()
    
    app = QApplication.instance() or QApplication([])
    dlg = MultiInputDialog(title, prompts or [], default_values or [], combo_items, parent)
    if dlg.exec() == QDialog.DialogCode.Accepted:
        return dlg.get_values()
    else:
        return None

class MultiInputDialog(QDialog):
    def __init__(self, title="录入", prompts=None, default_values=None, combo_items=None, 
                 header_text="", parent=None):
        super().__init__(parent)
        self.prompts = prompts or []
        self.default_values = default_values or []
        self.inputs = []
        self.combo_items = combo_items or []
        self.header_text = header_text
        
        # 字段名称映射（保持不变）
        self.field_names = {
            0: "project_name",   # 第一个输入框：项目名称
            1: "work_type",      # 第二个输入框：作业类型  
            2: "task_id",        # 第三个输入框：任务ID
            3: "workload1",      # 第四个输入框：工作量（写到工作量1字段）
            4: "workload2",      # 第五个输入框：初始框量（写到工作量2字段）
            5: "remark"          # 第六个输入框：备注
        }
        
        # ★★★ 设置醒目的窗口属性（保持不变）
        self.setWindowTitle(f"🔔 {title}")
        self.setWindowFlags(
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Dialog |
            Qt.WindowType.CustomizeWindowHint |
            Qt.WindowType.WindowTitleHint
        )
        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        
        # ★★★ 设置窗口样式（调整了字体大小和间距）
        self.setStyleSheet("""
            QDialog {
                background-color: white;
                border: 3px solid #ff4444;
                border-radius: 8px;
            }
            QLabel {
                font-size: 11px;  /* 从12px减小到11px */
                font-weight: bold;
                color: #333333;
                padding: 2px 5px;  /* 减小内边距 */
            }
            QComboBox {
                border: 2px solid #cccccc;
                border-radius: 4px;
                padding: 4px;  /* 从5px减小到4px */
                font-size: 11px;  /* 从12px减小到11px */
                min-height: 28px;  /* 从35px减小到28px */
            }
            QComboBox:focus {
                border-color: #ff4444;
            }
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 25px;  /* 从30px减小到25px */
                border-left: 1px solid #cccccc;
            }
            QComboBox::down-arrow {
                width: 14px;  /* 从16px减小到14px */
                height: 14px;  /* 从16px减小到14px */
            }
            QComboBox QAbstractItemView {
                border: 2px solid #ff4444;
                border-radius: 6px;
                background-color: white;
                selection-background-color: #fff0f0;
                font-size: 11px;  /* 从12px减小到11px */
                min-height: 25px;  /* 从30px减小到25px */
            }
            QPushButton {
                background-color: #ff4444;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 6px 12px;  /* 从8px16px减小到6px12px */
                font-size: 11px;  /* 从12px减小到11px */
                font-weight: bold;
                min-height: 32px;  /* 从40px减小到32px */
            }
            QPushButton:hover {
                background-color: #ff6666;
            }
            QPushButton:pressed {
                background-color: #cc3333;
            }
        """)
        
        self.init_ui()
        # ★★★ 自动聚焦到第一个输入框
        if self.inputs:
            self.inputs[0].setFocus()
        set_active_dialog(self)

    def init_ui(self):
        layout = QVBoxLayout()
        
        # 设置布局间距为更紧凑的值
        layout.setSpacing(4)
        layout.setContentsMargins(12, 12, 12, 12)

        # 头部标签（保持不变）
        if not self.header_text:
            header_text = "⏰ 检测到活动，请填写任务信息继续工作"
        else:
            header_text = self.header_text
            
        header_label = QLabel(header_text)
        header_label.setStyleSheet("""
            QLabel {
                font-size: 14px;
                font-weight: bold;
                color: #ff4444;
                padding: 8px;
                background-color: #fff0f0;
                border-radius: 6px;
                margin-bottom: 8px;
            }
        """)
        layout.addWidget(header_label)

        # 创建6个输入框
        from utils.constants import INPUT_LABELS
        input_labels = INPUT_LABELS
        
        for i, prompt in enumerate(input_labels):
            label = QLabel(prompt)
            label.setStyleSheet("font-size: 12px; font-weight: bold; color: #333333; padding: 1px 3px;")
            layout.addWidget(label)

            combo = QComboBox()
            combo.setEditable(True)
            combo.setMinimumHeight(28)
            combo.setStyleSheet("""
                QComboBox {
                    border: 2px solid #cccccc;
                    border-radius: 6px;
                    padding: 4px;
                    font-size: 11px;
                    min-height: 28px;
                }
                QComboBox:focus {
                    border-color: #ff4444;
                }
                QComboBox::drop-down {
                    subcontrol-origin: padding;
                    subcontrol-position: top right;
                    width: 25px;
                    border-left: 1px solid #cccccc;
                }
                QComboBox::down-arrow {
                    width: 14px;
                    height: 14px;
                }
                QComboBox QAbstractItemView {
                    border: 2px solid #ff4444;
                    border-radius: 6px;
                    background-color: white;
                    selection-background-color: #fff0f0;
                    font-size: 11px;
                    min-height: 25px;
                }
            """)
            
            # 设置默认值
            if i < len(self.default_values):
                combo.setCurrentText(self.default_values[i])
            
            # 特殊处理：作业类型下拉框
            if i == 1 and self.combo_items:
                combo.addItems(self.combo_items)
            else:
                # 其他输入框：加载历史记录
                self.load_field_history(combo, i)
            
            # ★★★ 修改：删除设置备注字段为只读的代码
            # 现在所有字段都是可编辑的，包括备注字段
            
            self.inputs.append(combo)
            layout.addWidget(combo)
            

        # 按钮区（保持不变）
        btn_layout = QHBoxLayout()
        ok_btn = QPushButton("✅ 确定并开始工作")
        cancel_btn = QPushButton("❌ 取消")
        
        ok_btn.setStyleSheet("""
            QPushButton {
                background-color: #ff4444;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 8px 16px;
                font-size: 12px;
                font-weight: bold;
                min-height: 32px;
            }
            QPushButton:hover {
                background-color: #ff6666;
            }
            QPushButton:pressed {
                background-color: #cc3333;
            }
        """)
        
        cancel_btn.setStyleSheet("""
            QPushButton {
                background-color: #666666;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 8px 16px;
                font-size: 12px;
                font-weight: bold;
                min-height: 32px;
            }
            QPushButton:hover {
                background-color: #888888;
            }
            QPushButton:pressed {
                background-color: #444444;
            }
        """)
        
        ok_btn.clicked.connect(self.accept)
        cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(ok_btn)
        btn_layout.addWidget(cancel_btn)
        layout.addLayout(btn_layout)

        self.setLayout(layout)
        self.resize(450, 350)
        self.center_on_screen()

    # ★★★ 添加缺失的 load_field_history 方法
    def load_field_history(self, combo, field_index):
        """加载指定字段的历史记录"""
        field_name = self.field_names.get(field_index)
        if not field_name:
            return
            
        manager = get_history_manager()
        if manager:
            history_items = manager.get_history(field_name, 10)
            print(f"[HISTORY] 为字段 {field_name} 加载历史记录: {history_items}")
            
            # 添加历史记录到下拉框
            for item in history_items:
                combo.addItem(item)

    def center_on_screen(self):
        """居中显示窗口"""
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        window_geometry = self.frameGeometry()
        center_point = screen_geometry.center()
        window_geometry.moveCenter(center_point)
        self.move(window_geometry.topLeft())

    def closeEvent(self, event):
        """窗口关闭时自动清理"""
        clear_active_dialog()
        super().closeEvent(event)
        
    def reject(self):
        """点击取消按钮时清理"""
        clear_active_dialog()
        super().reject()
        
    def accept(self):
        """点击确定按钮时清理"""
        clear_active_dialog()
        super().accept()

    def get_values(self):
        """返回用户填写的所有值，并保存到历史记录"""
        values = []
        for i, widget in enumerate(self.inputs):
            if hasattr(widget, 'currentText'):
                text = widget.currentText().strip()
                values.append(text)
                
                # ★★★ 保存到历史记录
                field_name = self.field_names.get(i)
                if text and field_name:
                    manager = get_history_manager()
                    if manager:
                        manager.add_history(field_name, text)
            else:
                values.append('')
        
        return values

class SingleInputDialog(QDialog):
    def __init__(self, title="输入", prompt="请输入:", password=False, field_name="", parent=None):
        super().__init__(parent)
        self.password = password
        self.prompt = prompt
        self.field_name = field_name  
        
        # ★★★ 设置醒目的窗口属性
        self.setWindowTitle(f"🔔 {title}")
        self.setWindowFlags(
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Dialog |
            Qt.WindowType.CustomizeWindowHint |
            Qt.WindowType.WindowTitleHint
        )
        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        
        # ★★★ 设置相同的样式
        self.setStyleSheet("""
            QDialog {
                background-color: white;
                border: 3px solid #ff4444;
                border-radius: 8px;
            }
            QLabel {
                font-size: 14px;
                font-weight: bold;
                color: #333333;
                padding: 5px;
            }
            QComboBox {
                border: 2px solid #cccccc;
                border-radius: 6px;
                padding: 10px;
                font-size: 14px;
                min-height: 35px;
            }
            QComboBox:focus {
                border-color: #ff4444;
            }
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 30px;
                border-left: 1px solid #cccccc;
            }
            QComboBox::down-arrow {
                width: 16px;
                height: 16px;
            }
            QComboBox QAbstractItemView {
                border: 2px solid #ff4444;
                border-radius: 6px;
                background-color: white;
                selection-background-color: #fff0f0;
                font-size: 14px;
                min-height: 30px;
            }
            QPushButton {
                background-color: #ff4444;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 12px 24px;
                font-size: 14px;
                font-weight: bold;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #ff6666;
            }
            QPushButton:pressed {
                background-color: #cc3333;
            }
        """)
        
        self.init_ui()
        set_active_dialog(self)

    def init_ui(self):
        layout = QVBoxLayout()
        
        # ★★★ 添加醒目标题
        header_label = QLabel("📝 请输入信息")
        header_label.setStyleSheet("""
            QLabel {
                font-size: 16px;
                font-weight: bold;
                color: #ff4444;
                padding: 10px;
                background-color: #fff0f0;
                border-radius: 6px;
                margin-bottom: 10px;
            }
        """)
        layout.addWidget(header_label)

        # 提示文字
        prompt_label = QLabel(self.prompt)
        prompt_label.setStyleSheet("font-size: 14px; color: #333333; padding: 5px;")
        layout.addWidget(prompt_label)

        # ★★★ 修改：如果是密码模式，使用 QLineEdit；否则使用 QComboBox
        if self.password:
            # 密码模式：使用 QLineEdit，不显示历史记录
            self.line = QLineEdit()
            self.line.setEchoMode(QLineEdit.EchoMode.Password)
            self.line.setMinimumHeight(35)
            layout.addWidget(self.line)
        else:
            # 普通模式：使用 QComboBox，显示历史记录
            self.combo = QComboBox()
            self.combo.setEditable(True)
            self.combo.setMinimumHeight(35)
            layout.addWidget(self.combo)
            
            # 加载历史记录（非密码模式）
            self.load_history()

        # 按钮布局
        btn_layout = QHBoxLayout()
        ok_btn = QPushButton("✅ 确定")
        cancel_btn = QPushButton("❌ 取消")
        ok_btn.clicked.connect(self.accept)
        cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(ok_btn)
        btn_layout.addWidget(cancel_btn)
        layout.addLayout(btn_layout)

        self.setLayout(layout)
        
        # ★★★ 设置合适的窗口大小
        self.resize(450, 200)
        self.center_on_screen()

    def load_history(self):
        """加载该字段的历史记录"""
        if not self.field_name:
            return
            
        manager = get_history_manager()
        if manager:
            history_items = manager.get_history(self.field_name, 10)
            print(f"[HISTORY] 为字段 {self.field_name} 加载历史记录: {history_items}")
            
            # 清空现有项目并添加历史记录
            self.combo.clear()
            for item in history_items:
                self.combo.addItem(item)
            
            # 如果有历史记录，设置第一个为当前文本
            if history_items:
                self.combo.setCurrentText(history_items[0])

    def center_on_screen(self):
        """居中显示窗口"""
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        window_geometry = self.frameGeometry()
        center_point = screen_geometry.center()
        window_geometry.moveCenter(center_point)
        self.move(window_geometry.topLeft())

    def get_text(self):
        """获取用户输入的文本"""
        if self.password:
            # 密码模式：从 QLineEdit 获取
            text = self.line.text().strip()
        else:
            # 普通模式：从 QComboBox 获取
            text = self.combo.currentText().strip()
            
            # 保存到历史记录（非密码模式）
            if text and self.field_name:
                manager = get_history_manager()
                if manager:
                    manager.add_history(self.field_name, text)
        
        return text
    
    def closeEvent(self, event):
        """窗口关闭时自动清理"""
        clear_active_dialog()
        super().closeEvent(event)
        
    def reject(self):
        """点击取消按钮时清理"""
        clear_active_dialog()
        super().reject()
        
    def accept(self):
        """点击确定按钮时清理"""
        clear_active_dialog()
        super().accept()

def qt_single_input(title="输入", prompt="请输入:", password=False, field_name="", parent=None):
    """
    单行输入对话框
    field_name: 字段名称，用于历史记录管理（如 "project_name", "task_id" 等）
    """
    # ★★★ 先关闭可能存在的旧窗口 ★★★
    close_active_dialog()
    
    app = QApplication.instance() or QApplication([])
    dlg = SingleInputDialog(title, prompt, password, field_name, parent)
    if dlg.exec() == QDialog.DialogCode.Accepted:
        return dlg.get_text()
    else:
        return None

class ComboInputDialog(QDialog):
    def __init__(self, title="请选择", prompt="请选择一项：", choices=None, default_value=""):
        super().__init__(None)
        
        # ★★★ 设置醒目的窗口属性
        self.setWindowTitle(f"🔔 {title}")
        self.setWindowFlags(
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Dialog |
            Qt.WindowType.CustomizeWindowHint |
            Qt.WindowType.WindowTitleHint
        )
        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        
        # ★★★ 设置相同的样式
        self.setStyleSheet("""
            QDialog {
                background-color: white;
                border: 3px solid #ff4444;
                border-radius: 8px;
            }
            QLabel {
                font-size: 12px;
                font-weight: bold;
                color: #333333;
            }
            QComboBox {
                border: 2px solid #cccccc;
                border-radius: 4px;
                padding: 5px;
                font-size: 12px;
            }
            QComboBox:focus {
                border-color: #ff4444;
            }
            QPushButton {
                background-color: #ff4444;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                font-size: 12px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #ff6666;
            }
            QPushButton:pressed {
                background-color: #cc3333;
            }
        """)
        
        self.choices = choices or []
        self.prompt = prompt
        self.default_value = default_value
        self.init_ui()
        set_active_dialog(self)  # 注册自己为活跃对话框

    def init_ui(self):
        layout = QVBoxLayout()
        
        # ★★★ 添加醒目标题
        header_label = QLabel("📋 请选择作业类型")
        header_label.setStyleSheet("""
            QLabel {
                font-size: 14px;
                font-weight: bold;
                color: #ff4444;
                padding: 8px;
                background-color: #fff0f0;
                border-radius: 4px;
                margin-bottom: 10px;
            }
        """)
        layout.addWidget(header_label)
        
        layout.addWidget(QLabel(self.prompt))
        self.combo = QComboBox()
        self.combo.addItems(self.choices)
        
        # 设置默认值
        if self.default_value and self.default_value in self.choices:
            index = self.choices.index(self.default_value)
            self.combo.setCurrentIndex(index)
        
        layout.addWidget(self.combo)

        btn_layout = QHBoxLayout()
        ok_btn = QPushButton("✅ 确定")
        cancel_btn = QPushButton("❌ 取消")
        ok_btn.clicked.connect(self.accept)
        cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(ok_btn)
        btn_layout.addWidget(cancel_btn)
        layout.addLayout(btn_layout)
        self.setLayout(layout)
        
        # ★★★ 设置合适大小并居中
        self.resize(350, 200)
        self.center_on_screen()

    def center_on_screen(self):
        """居中显示窗口"""
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        window_geometry = self.frameGeometry()
        center_point = screen_geometry.center()
        window_geometry.moveCenter(center_point)
        self.move(window_geometry.topLeft())

    def get_choice(self):
        return self.combo.currentText()

    def closeEvent(self, event):
        """窗口关闭时自动清理"""
        clear_active_dialog()
        super().closeEvent(event)
        
    def reject(self):
        """点击取消按钮时清理"""
        clear_active_dialog()
        super().reject()
        
    def accept(self):
        """点击确定按钮时清理"""
        clear_active_dialog()
        super().accept()

def qt_combo_input(title="请选择", prompt="请选择一项：", choices=None, default_value="", parent=None):
    if choices is None:
        choices = []
    
    # ★★★ 先关闭可能存在的旧窗口 ★★★
    close_active_dialog()
    
    app = QApplication.instance() or QApplication([])
    dlg = ComboInputDialog(title, prompt, choices, default_value, parent)
    if dlg.exec() == QDialog.DialogCode.Accepted:
        return dlg.get_choice()
    else:
        return None

# 在 qt6_input_dialog.py 中修改 WorkloadDialog 类

class WorkloadDialog(QDialog):
    """一次弹框：输入工作量 + 选提交/继续"""
    def __init__(self, parent=None):
        super().__init__(parent)
        
        # ★★★ 设置醒目的窗口属性
        self.setWindowTitle("🔔 记录工作量")
        self.setWindowFlags(
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Dialog |
            Qt.WindowType.CustomizeWindowHint |
            Qt.WindowType.WindowTitleHint
        )
        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        
        # ★★★ 设置相同的样式
        self.setStyleSheet("""
            QDialog {
                background-color: white;
                border: 3px solid #ff4444;
                border-radius: 8px;
            }
            QLabel {
                font-size: 14px;
                font-weight: bold;
                color: #333333;
                padding: 8px;
            }
            QComboBox {
                border: 2px solid #cccccc;
                border-radius: 6px;
                padding: 10px;
                font-size: 14px;
                min-height: 35px;
            }
            QComboBox:focus {
                border-color: #ff4444;
            }
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 30px;
                border-left: 1px solid #cccccc;
            }
            QComboBox::down-arrow {
                width: 16px;
                height: 16px;
            }
            QComboBox QAbstractItemView {
                border: 2px solid #ff4444;
                border-radius: 6px;
                background-color: white;
                selection-background-color: #fff0f0;
                font-size: 14px;
                min-height: 30px;
            }
            QPushButton {
                background-color: #ff4444;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 12px 24px;
                font-size: 14px;
                font-weight: bold;
                min-height: 40px;
                min-width: 120px;
            }
            QPushButton:hover {
                background-color: #ff6666;
            }
            QPushButton:pressed {
                background-color: #cc3333;
            }
        """)
        
        self.init_ui()
        set_active_dialog(self)

    def init_ui(self):
        layout = QVBoxLayout()
        
        # ★★★ 添加醒目标题
        header_label = QLabel("📊 记录工作量")
        header_label.setStyleSheet("""
            QLabel {
                font-size: 16px;
                font-weight: bold;
                color: #ff4444;
                padding: 12px;
                background-color: #fff0f0;
                border-radius: 6px;
                margin-bottom: 15px;
            }
        """)
        layout.addWidget(header_label)

        # 输入框
        prompt_label = QLabel("请输入工作量（数字）：")
        prompt_label.setStyleSheet("font-size: 14px; color: #333333; padding: 8px;")
        layout.addWidget(prompt_label)
        
        # ★★★ 修改：使用 QComboBox 替代 QLineEdit
        self.combo = QComboBox()
        self.combo.setEditable(True)  # 设置为可编辑
        
        # 设置输入框样式
        self.combo.setMinimumHeight(35)
        layout.addWidget(self.combo)

        # ★★★ 新增：加载工作量历史记录
        self.load_workload_history()

        # 按钮区
        btn_layout = QHBoxLayout()
        submit_btn = QPushButton("✅ 提交任务")
        continue_btn = QPushButton("🔄 继续任务")
        
        submit_btn.clicked.connect(lambda: self.done(1))   # 1 表示提交
        continue_btn.clicked.connect(lambda: self.done(2)) # 2 表示继续
        
        btn_layout.addWidget(submit_btn)
        btn_layout.addWidget(continue_btn)
        layout.addLayout(btn_layout)

        self.setLayout(layout)
        
        # ★★★ 设置合适的窗口大小
        self.resize(450, 250)
        self.center_on_screen()

    def load_workload_history(self):
        """加载工作量历史记录"""
        manager = get_history_manager()
        if manager:
            # 使用 "workload1" 作为字段名来保存工作量历史
            history_items = manager.get_history("workload1", 10)
            print(f"[HISTORY] 加载工作量历史记录: {history_items}")
            
            # 清空现有项目并添加历史记录
            self.combo.clear()
            for item in history_items:
                self.combo.addItem(item)
            
            # 如果有历史记录，设置第一个为当前文本
            if history_items:
                self.combo.setCurrentText(history_items[0])

    def center_on_screen(self):
        """居中显示窗口"""
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        window_geometry = self.frameGeometry()
        center_point = screen_geometry.center()
        window_geometry.moveCenter(center_point)
        self.move(window_geometry.topLeft())

    def get_values(self):
        """返回工作量数字"""
        text = self.combo.currentText().strip()
        
        # ★★★ 新增：保存到历史记录
        if text:
            manager = get_history_manager()
            if manager:
                manager.add_history("workload1", text)
        
        return text

    def closeEvent(self, event):
        clear_active_dialog()
        super().closeEvent(event)
        
    def reject(self):
        clear_active_dialog()
        super().reject()
        
    def accept(self):
        clear_active_dialog()
        super().accept()

class TwoButtonDialog(QDialog):
    """两个按钮的选择对话框"""
    def __init__(self, title="选择", prompt="请选择：", button1_text="确定", button2_text="取消", parent=None):
        super().__init__(parent)
        
        # ★★★ 设置醒目的窗口属性
        self.setWindowTitle(f"🔔 {title}")
        self.setWindowFlags(
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Dialog |
            Qt.WindowType.CustomizeWindowHint |
            Qt.WindowType.WindowTitleHint
        )
        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        
        # ★★★ 设置相同的样式
        self.setStyleSheet("""
            QDialog {
                background-color: white;
                border: 3px solid #ff4444;
                border-radius: 8px;
            }
            QLabel {
                font-size: 14px;
                font-weight: bold;
                color: #333333;
                padding: 8px;
            }
            QPushButton {
                border: none;
                border-radius: 6px;
                padding: 12px 24px;
                font-size: 14px;
                font-weight: bold;
                min-height: 40px;
                min-width: 120px;
            }
        """)
        
        self.title = title
        self.prompt = prompt
        self.button1_text = button1_text
        self.button2_text = button2_text
        
        self.init_ui()
        set_active_dialog(self)  # 注册自己为活跃对话框

    def init_ui(self):
        layout = QVBoxLayout()
        
        # ★★★ 添加醒目标题
        header_label = QLabel(f"📋 {self.title}")
        header_label.setStyleSheet("""
            QLabel {
                font-size: 16px;
                font-weight: bold;
                color: #ff4444;
                padding: 12px;
                background-color: #fff0f0;
                border-radius: 6px;
                margin-bottom: 15px;
            }
        """)
        layout.addWidget(header_label)

        # 提示文字
        prompt_label = QLabel(self.prompt)
        prompt_label.setStyleSheet("font-size: 14px; color: #333333; padding: 10px;")
        layout.addWidget(prompt_label)

        # 按钮区
        btn_layout = QHBoxLayout()
        
        # 按钮1 - 开始新任务
        btn1 = QPushButton(f"✅ {self.button1_text}")
        btn1.setStyleSheet("""
            QPushButton {
                background-color: #ff4444;
                color: white;
            }
            QPushButton:hover {
                background-color: #ff6666;
            }
            QPushButton:pressed {
                background-color: #cc3333;
            }
        """)
        btn1.clicked.connect(lambda: self.done(1))
        
        # 按钮2 - 休息一下
        btn2 = QPushButton(f"🛑 {self.button2_text}")
        btn2.setStyleSheet("""
            QPushButton {
                background-color: #666666;
                color: white;
            }
            QPushButton:hover {
                background-color: #888888;
            }
            QPushButton:pressed {
                background-color: #444444;
            }
        """)
        btn2.clicked.connect(lambda: self.done(2))
        
        btn_layout.addWidget(btn1)
        btn_layout.addWidget(btn2)
        layout.addLayout(btn_layout)

        self.setLayout(layout)
        
        # ★★★ 设置合适的窗口大小
        self.resize(400, 200)
        self.center_on_screen()

    def center_on_screen(self):
        """居中显示窗口"""
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        window_geometry = self.frameGeometry()
        center_point = screen_geometry.center()
        window_geometry.moveCenter(center_point)
        self.move(window_geometry.topLeft())
    
    def closeEvent(self, event):
        clear_active_dialog()
        super().closeEvent(event)
        
    def reject(self):
        clear_active_dialog()
        super().reject()
        
    def accept(self):
        clear_active_dialog()
        super().accept()

# 在 qt6_input_dialog.py 中修改 qt_workload_box 函数
def qt_workload_box(parent=None):
    """确保在主线程中执行"""
    try:
        app = QApplication.instance()
        if app is None:
            log('[QT-INPUT] 错误: 没有QApplication实例')
            return None, None
            
        dlg = WorkloadDialog(parent)
        code = dlg.exec()
        action = "提交任务" if code == 1 else "继续任务" if code == 2 else None
        workload = dlg.get_values()   
        return action, workload
    except Exception as e:
        log(f'[QT-INPUT] 工作量对话框异常: {e}')
        return None, None
  
if __name__ == "__main__":
    choice = qt_combo_input("作业类型", "请选择本次作业类型：", ["数据更新", "初审", "复审"])
    print("你选中的是：", choice)